package org.feng.qqimageview;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.widget.ImageView;

public class QQImageView extends ImageView {
	private static final String TAG = "QQImageView";
	private int mBackgroundColor = Color.parseColor("#EBEBEB");
	private int mProgressColor = Color.WHITE;
	private boolean mIsLoading = false;

	private int mProgress = 0;

	private Paint mBackgroundPaint;
	private Paint mProgressPaint;

	private float mCenterX;
	private float mCenterY;

	private float mCircleRadiu;
	private float mDefaultCircleRadiu = 52;

	private float mInCricleRadiu;

	private RectF mCircleRect;

	private Drawable mFailDrawable;

	public interface OnImageDownloadedListener {
		public void download(Bitmap bitmap);
	}
	public int getBackgroundColor() {
		return mBackgroundColor;
	}

	public void setBackgroundColor(int mBackgroundColor) {
		this.mBackgroundColor = mBackgroundColor;
	}

	public int getProgressColor() {
		return mProgressColor;
	}

	public void setProgressColor(int mProgressColor) {
		this.mProgressColor = mProgressColor;
	}

	public Drawable getFailDrawable() {
		return mFailDrawable;
	}

	public void setFailDrawable(Drawable failDrawable) {
		this.mFailDrawable = failDrawable;
	}
	private OnImageDownloadedListener mOnImageDownloadedListener;

	public void setOnImageDownloadedListener(OnImageDownloadedListener listener) {
		mOnImageDownloadedListener = listener;
	}

	public QQImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);

		if (null != attrs) {
			TypedArray typeArray = context.obtainStyledAttributes(attrs,
					R.styleable.QQImageView);
			mFailDrawable = typeArray
					.getDrawable(R.styleable.QQImageView_failImage);
			mBackgroundColor = typeArray.getColor(
					R.styleable.QQImageView_backgroundColor, mBackgroundColor);
			mProgressColor = typeArray.getColor(
					R.styleable.QQImageView_progressColor, mProgressColor);
			typeArray.recycle();
		}
		mBackgroundPaint = new Paint();
		mBackgroundPaint.setColor(mBackgroundColor);
		mBackgroundPaint.setAntiAlias(true);

		mProgressPaint = new Paint();
		mProgressPaint.setColor(mProgressColor);
		mProgressPaint.setAntiAlias(true);
		mCircleRect = new RectF();
		
		setMinimumHeight((int) (mDefaultCircleRadiu*4));
		setMinimumWidth((int)mDefaultCircleRadiu*4);
	}

	public QQImageView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public QQImageView(Context context) {
		this(context, null, 0);
	}
	
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if (mIsLoading) {
			mCenterX = getWidth() / 2;
			mCenterY = getHeight() / 2;
			mCircleRadiu = getWidth() / 4f > getHeight() / 4f ? getHeight() / 4f
					: getWidth() / 4f;
			if (mCircleRadiu > mDefaultCircleRadiu) {
				mCircleRadiu = mDefaultCircleRadiu;
			}
			mInCricleRadiu = mCircleRadiu - 10;
			canvas.drawCircle(mCenterX, mCenterY, mCircleRadiu, mProgressPaint);
			mCircleRect.bottom = mCenterY + mInCricleRadiu+1;
			mCircleRect.top = mCenterY - mInCricleRadiu-1;
			mCircleRect.left = mCenterX - mInCricleRadiu-1;
			mCircleRect.right = mCenterX + mInCricleRadiu+1;
			canvas.drawCircle(mCenterX, mCenterY, mInCricleRadiu,mBackgroundPaint);
			canvas.drawArc(mCircleRect, -90, (mProgress * 360f / 100), true,
					mProgressPaint);
		}
	}

	public void setImageUrl(String url) {
		new BitmapDownLoadTask().execute(url);
	}

	class BitmapDownLoadTask extends AsyncTask<String, Integer, Bitmap> {

		@Override
		protected Bitmap doInBackground(String... params) {
			mIsLoading = true;
			Bitmap bitmap = null;
			try {
				URL url = new URL(params[0]);
				URLConnection conn = url.openConnection();
				conn.connect();
				int totalLength = conn.getContentLength();
				InputStream is = conn.getInputStream();
				byte[] totalBuffer = new byte[totalLength];
				byte[] buffer = new byte[1024];
				int length = 0;
				int currentLength = 0;
				while ((length = is.read(buffer)) > 0) {
					for (int i = 0; i < length; i++) {
						totalBuffer[currentLength + i] = buffer[i];
					}
					currentLength += length;
					int pecent = (int) (((float) (currentLength) / totalLength) * 100);
					publishProgress(pecent);
				}
				bitmap = BitmapFactory.decodeByteArray(totalBuffer, 0,
						totalBuffer.length);
			} catch (MalformedURLException e1) {
				e1.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return bitmap;
		}

		private void setFail() {
			mIsLoading = false;
			if (null != mFailDrawable) {
				setImageDrawable(mFailDrawable);
			}
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			mProgress = values[0];
			invalidate();
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
			mIsLoading = false;
			if (null != result) {
				setImageBitmap(result);
				if (null != mOnImageDownloadedListener) {
					mOnImageDownloadedListener.download(result);
				}
			}else{
				setFail();
			}
		}
	}
}
